﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CSharp.Infrastructure
{
    /// <summary>
    /// 锁
    /// </summary>
    public class LockHelper
    {
        /// <summary>
        /// 锁
        /// </summary>
        private static List<Tuple<string, Semaphore>> lockList = new List<Tuple<string, Semaphore>>();

        /// <summary>
        /// 取锁
        /// </summary>
        /// <returns></returns>
        public static void GetLock<T>()
        {
            // 通过T拿锁
            var key = typeof(T).FullName;
            Semaphore semaphore = null;
            lock (lockList)
            {
                var item = lockList.Find(a => a.Item1 == key);
                if (item == null)
                {
                    semaphore = new Semaphore(1, 1);
                    lockList.Add(Tuple.Create(typeof(T).FullName, semaphore));
                }
                else
                {
                    semaphore = item.Item2;
                }
            }

            semaphore.WaitOne();
        }

        /// <summary>
        /// 释放锁
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public static void ReleaseLock<T>()
        {
            // 通过T拿锁
            var key = typeof(T).FullName;
            lock (lockList)
            {
                var item = lockList.Find(a => a.Item1 == key);

                item.Item2.Release();
            }
        }
    }
}
